﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using System.Configuration;
using NHibernate.Criterion;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Mapping;
using RepositoriesInterfaces;

namespace Repositories
{
    public class BaseRepository<T>
    {
        private ISession session = null;
        public ISession _session
        {
            get
            {
                return session;
            }
            set
            {
                session = value;
            }
        }
        public IList<T> GetAll()
        {
            IList<T> list;
            session.BeginTransaction();
            list = session.CreateCriteria(typeof(T)).List<T>();
            session.Transaction.Commit();

            return list;
        }
        public T GetByID(int id)
        {
            T list;
            session.BeginTransaction();
            list = session.Get<T>(id);
            session.Transaction.Commit();
            return list;
        }
        public void Save(T obj)
        {            
            session.BeginTransaction();
            session.Save(obj);
            session.Transaction.Commit();
        }
        public void Delete(T obj)
        {            
            session.BeginTransaction();
            session.Delete(obj);
            session.Transaction.Commit();
        }
        public void SaveOrUpdate(T obj)
        {
            session.BeginTransaction();
            session.SaveOrUpdate(obj);
            session.Transaction.Commit();
        }
        public void DeleteByID(string idPropertyName, int objId)
        {
            session.BeginTransaction();
            var result = session.CreateCriteria(typeof(T))
                                    .Add(Restrictions.Eq(idPropertyName, objId))
                                    .List<T>();
            if (result.Count > 0)
            {
                session.Delete(result[0]);
            }
            session.Transaction.Commit();
        }
        public IList<T> GetByPropertyName(string idPropertyName, string pvalue)
        {
            IList<T> list;            
            session.BeginTransaction();
            list = session.CreateCriteria(typeof(T))
                                    .Add(Restrictions.Like(idPropertyName, pvalue, MatchMode.Anywhere))
                                    .List<T>();
            session.Transaction.Commit();
            return list;
        }
    }
}